package com.mi.system.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mi.system.dto.query.DictItemQueryDTO;
import com.mi.system.dto.request.DictItemRequestDTO;
import com.mi.system.entity.DictItem;
import com.mi.system.mapper.DictItemMapper;
import com.mi.system.vo.DictItemBriefVO;
import com.mi.system.vo.DictItemVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * Dict item service
 *
 * @author jin_huaquan
 * @version 1.0
 * @date 2021/11/1 13:59
 */
@Service
@RequiredArgsConstructor
public class DictItemServiceImpl extends ServiceImpl<DictItemMapper, DictItem> implements DictItemService {


    @Override
    public Page<DictItemVO> listDictItem(Page page, DictItemQueryDTO query) {
        return baseMapper.selectByPage(page, query);
    }

    @Override
    public List<DictItemBriefVO> listDictItem(String type) {
        return baseMapper.selectByType(type);
    }

    @Override
    @Transactional(rollbackFor = TransactionException.class)
    public boolean saveDictItem(DictItemRequestDTO request) {
        Assert.isFalse(existsByDictIdAndValue(request.getDictId(), request.getValue()), "已存在相同数据值的字典项");

        DictItem dictItem = new DictItem();

        BeanUtil.copyProperties(request, dictItem);

        return this.save(dictItem);
    }

    @Override
    @Transactional(rollbackFor = TransactionException.class)
    public boolean updateDictItem(Long id, DictItemRequestDTO request) {
        DictItem dictItem = baseMapper.selectById(id);
        Assert.notNull(dictItem, "未找到对应的字典项");

        if (!Objects.equals(dictItem.getValue(), request.getDictId())) {
            Assert.isFalse(existsByDictIdAndValue(request.getDictId(), request.getValue()), "已存在相同数据值的字典项");
        }

        BeanUtil.copyProperties(request, dictItem);

        return this.updateById(dictItem);
    }

    @Override
    @Transactional(rollbackFor = TransactionException.class)
    public DictItem removeDictItem(Long id) {
        DictItem dictItem = baseMapper.selectById(id);
        Assert.notNull(dictItem, "未找到对应的字典项");

        baseMapper.deleteById(dictItem);

        return dictItem;
    }

    /**
     * whether exists with dict id and value
     *
     * @param dictId dict id
     * @param value  value
     * @return whether exists
     */
    private boolean existsByDictIdAndValue(Long dictId, String value) {
        return baseMapper.selectCount(Wrappers.<DictItem>lambdaQuery()
                .eq(DictItem::getDictId, dictId)
                .eq(DictItem::getValue, value)) > 0;
    }
}
